package com.wang.service.impl;

import com.wang.dao.UserRepository;
import com.wang.entity.User;
import com.wang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @Classname UserServiceImpl
 * @Description TODO
 * @Date 2024/5/24 11:18
 * @Created by pc
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    //Cacheable 用于查询缓存
    // value 相当于缓存中的key前缀
    // key 缓存中key的后缀
    // unless 如果是空值就不放入缓存
    @Cacheable(value = "user",key = "#id",unless = "#result eq null")
    @Override
    public User findById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @CachePut(value = "user",key = "#result.id",unless = "#result eq null")
    @Override
    public User save(User user) {
        return userRepository.save(user);
    }

    @CacheEvict(value = "user",key = "#id")
    @Override
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }
}
